﻿using System;
using System.IO;
using System.Reflection;
using Skynet.CommonLibrary.Extension;
using Skynet.CommonLibrary.ThreadRefreshTime.RefreshElement;

namespace Skynet.CommonLibrary.ThreadRefreshTime.Extension
{
    /// <summary>
    /// 刷新任务实体 扩展  用于根据方法参数进行反射
    /// </summary>
    ///<remarks>
    /// 作者：         李志强
    /// 开发时间：  2011-03-28
    /// </remarks>
    public static class RefreshTaskXmlExtension
    {
        public static void StartTask(this RefreshTaskXmlElement entity,params object[] values)
        {
            Action refAction = GetAction(entity.ActionAssableName,
                    entity.ActionClassName,
                     entity.ActionMethodName,
                     values);
            string xml = RefreshManageFactory.GetRefreshManage.RefreshTaskToXml(entity);
            RefreshManageFactory.GetRefreshManage.AddTask(new StringReader(xml), refAction);
        }

        /// <summary>
        /// 执行方法配置
        /// </summary>
        private static Action GetAction(string assemblyname, string classname, string methodname,object[] values)
        {
            var instance = Assembly.Load(assemblyname.Split('.')[0]).CreateInstance(assemblyname + "." + classname);
            if (instance != null)
            {
                Type t = instance.GetType();
                MethodInfo info = t.GetMethod(methodname, BindingFlags.Public | BindingFlags.Instance);
            
                //TODO:生成动态委托
                Type delegateType =  t.GetMethodInfoOrParams(methodname, values).CreateCustomDelegate();

                Delegate methodDelegate = Delegate.CreateDelegate(delegateType, null, info);
                Action action = new Action(() => methodDelegate.DynamicInvoke(values));
                return action;
            }
            return null;
        }
    }
}
